package wec_wallet.ebo.com.activity.options;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.BeanManager;
import wec_wallet.ebo.com.utils.Functions;

public class
ChangePhoneActivity extends MyBaseActivity {
    @BindView(R.id.actionbar_back)
    RelativeLayout actionbar_back;
    @BindView(R.id.tv_oldphone)
    TextView tv_oldphone;
    @BindView(R.id.et_oldphonecode)
    EditText et_oldphonecode;
    @BindView(R.id.et_new_phone)
    EditText et_new_phone;
    @BindView(R.id.et_new_phonecode)
    EditText et_new_phonecode;
    @BindView(R.id.btn_get_code_oldphone)
    Button btn_get_code_oldphone;
    @BindView(R.id.btn_get_code_new_phone)
    Button btn_get_code_new_phone;
    @BindView(R.id.btn_ok)
    Button btn_ok;
    @BindView(R.id.spinner_area_number)
    Spinner spinner_area_number;
    //获取旧手机验证码
    Handler mhandle_getcode_oldphone = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    Integer v = (Integer) msg.obj;
                    if (v > 0) {
                        sendMessageDelayed(obtainMessage(1, v - 1), 1000);
                        btn_get_code_oldphone.setText(v.toString() + "s");
                    } else {
                        btn_get_code_oldphone.setClickable(true);
                        btn_get_code_oldphone.setText(getResources().getString(R.string.get_phone_code));
                    }
                    break;
            }
        }
    };
    //获取新手机验证码
    Handler mhandle_getcode_newphone = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    Integer v = (Integer) msg.obj;
                    if (v > 0) {
                        sendMessageDelayed(obtainMessage(1, v - 1), 1000);
                        btn_get_code_new_phone.setText(v.toString() + "s");
                    } else {
                        btn_get_code_new_phone.setClickable(true);
                        btn_get_code_new_phone.setText(getResources().getString(R.string.get_phone_code));
                    }
                    break;
            }
        }
    };
    private String prefix;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        String oldphone = I_Share.readAccountUsername_Phone();
        oldphone = bassproject.ebo.com.ebobass.utils.StringUtil.toEncryption(oldphone);
        tv_oldphone.setText(oldphone);
        if (BeanManager.areaNumber == null) {
            Functions.getPhonePrefix(this, new ListenerGet_Phone_Prefix());
        } else {
            setSpinner();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onClick_Back();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    //返回
    @OnClick(R.id.actionbar_back)
    void onClick_Back() {
        finish();
    }

    //获取旧手机验证码
    @OnClick(R.id.btn_get_code_oldphone)
    void onClick_GetOde_Old_Phone() {
        Map<String, Object> postParams;
        //获取验证码
        postParams = new HashMap<String, Object>();
//        postParams.put("lan", I_Share.getLanguageType_String());
        postParams.put("token", I_Share.readAccountToken());
        postParams.put("uid", I_Share.readAccountUserid());
        Functions.post(this, URLs.CHANGE_PHONE_GET_OLD_CODE, postParams, new ListenerGetCode_OldPhone(), true, true);
    }

    //获取新手机验证码
    @OnClick(R.id.btn_get_code_new_phone) void onClick_GetOde_New_Phone() {
        String new_phone = et_new_phone.getText().toString();
        //手机号是否为空
        if (new_phone == null || TextUtils.isEmpty(new_phone)) {
            IToast.show(getResources().getString(R.string.change_phone_hint_input_new_phone));
            return;
        }
        Map<String, Object> postParams;
        //获取验证码
        postParams = new HashMap<String, Object>();
//        postParams.put("lan", I_Share.getLanguageType_String());
        postParams.put("token", I_Share.readAccountToken());
        postParams.put("uid", I_Share.readAccountUserid());

        postParams.put("mobile", new_phone);
        Functions.post(this, URLs.CHANGE_PHONE_GET_NEW_CODE, postParams, new ListenerGetCode_NewPhone(), true, true);
    }

    //提交换绑
    @OnClick(R.id.btn_ok) void onClick_OK() {
        String new_phone, old_code, new_code;

        new_phone = et_new_phone.getText().toString();
        old_code = et_oldphonecode.getText().toString();
        new_code = et_new_phonecode.getText().toString();
        //新手机号是否为空
        if (new_phone == null || TextUtils.isEmpty(new_phone)) {
            IToast.show(getResources().getString(R.string.change_phone_hint_input_new_phone));
            return;
        }
        //旧验证码是否为空
        if (old_code == null || TextUtils.isEmpty(old_code)) {
            IToast.show(getResources().getString(R.string.change_phone_hint_input_old_phone_code));
            return;
        }
        //新验证码是否为空
        if (new_code == null || TextUtils.isEmpty(new_code)) {
            IToast.show(getResources().getString(R.string.change_phone_hint_input_new_phone_code));
            return;
        }

        Map<String, Object> postParams;
        //获取验证码
        postParams = new HashMap<String, Object>();
//        postParams.put("lan", I_Share.getLanguageType_String());
        postParams.put("token", I_Share.readAccountToken());
        postParams.put("uid", I_Share.readAccountUserid());
        postParams.put("mobile", new_phone);
        postParams.put("new_code", new_code);
        postParams.put("old_code", old_code);
        Functions.post(this, URLs.CHANGE_PHONE, postParams, new ListenerChangePhone(new_phone), true, true);

    }

    @Override
    public void onClick(View v) {
    }

    private void setSpinner() {
        //适配器
        ArrayAdapter arrAdapter = new ArrayAdapter<String>(this, R.layout.login_spinner_item_black, BeanManager.areaNumber.getNumbers());
        //设置样式
        arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器

        spinner_area_number.setAdapter(arrAdapter);
        spinner_area_number.setSelection(BeanManager.areaNumber.getNumbers().size() - 1, true);
        spinner_area_number.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                                          @Override
                                                          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                                              prefix = spinner_area_number.getSelectedItem().toString().substring(1);
                                                              Log.d("LGY", "prefix=" + prefix);
                                                          }

                                                          @Override
                                                          public void onNothingSelected(AdapterView<?> parent) {

                                                          }
                                                      }
        );
        spinner_area_number.setSelection(0);
    }

    //接口start======================================================
    //获取手机验证码-旧
    class ListenerGetCode_OldPhone implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("获取手机验证码-旧 result=" + result);
            if (null != result) {

                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }

                    if (error == 0) {
                        IToast.show(getResources().getString(R.string.get_phone_code_success));
                        //成功
                        btn_get_code_oldphone.setClickable(false);
                        mhandle_getcode_oldphone.sendMessage(mhandle_getcode_oldphone.obtainMessage(1, getResources().getInteger(R.integer.resend_smscode)));
                    }
                    else{
                        //重新登陆
                        if(resultObject.has("is_auth")&&resultObject.getString("is_auth").equals("0")){
                            Functions.relogin(ChangePhoneActivity.this);
                        }
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());

                }
            }
        }
    }
    //接口end==========================================================

    //获取手机验证码-新
    class ListenerGetCode_NewPhone implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("获取手机验证码-旧 result=" + result);
            if (null != result) {

                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }

                    if (error == 0) {
                        IToast.show(getResources().getString(R.string.get_phone_code_success));
                        //成功
                        btn_get_code_new_phone.setClickable(false);
                        mhandle_getcode_newphone.sendMessage(mhandle_getcode_newphone.obtainMessage(1, getResources().getInteger(R.integer.resend_smscode)));
                    }
                    else{
                        //重新登陆
                        if(resultObject.has("is_auth")&&resultObject.getString("is_auth").equals("0")){
                            Functions.relogin(ChangePhoneActivity.this);
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());

                }
            }
        }
    }

    //换绑手机号
    class ListenerChangePhone implements IHttpPostListener {
        private String phone;
        public ListenerChangePhone(String _phone) {
            phone = _phone;
        }

        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("换绑手机号 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }
                    if (error == 0) {
                        //换绑成功，重新登录
                        IToast.show(getResources().getString(R.string.change_phone_success));
                        I_Share.saveAccount(phone, null, null, null, null);
                        Functions.relogin(ChangePhoneActivity.this);
                        finish();
                    }else{
                        //重新登陆
                        if(resultObject.has("is_auth")&&resultObject.getString("is_auth").equals("0")){
                            Functions.relogin(ChangePhoneActivity.this);
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }
    }

    //获取手机区号
    class ListenerGet_Phone_Prefix implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("获取手机区号 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }

                    if (error == 0) {
                        //成功
                        JSONArray jsonArray = new JSONArray(resultObject.getString("data"));
                        List<String> list = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            list.add("+" + jsonArray.getJSONObject(i).getString("prefix"));
                            Lg.d("list " + i + " = " + list.get(i));
                        }
                        BeanManager.initAreaNumber(list);
                        setSpinner();
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }
    }
}
